//
//  WeatherRequest.swift
//  Weather
//
//  Created by jingjing jia on 2023/4/26.
//

import Foundation
import Combine


protocol WeatherWebRepository: WebRepository {
    func fetchLiveWeather(city: CityModel) -> AnyPublisher<WeatherLiveModel, Error>
    func fetchForecastWeather(city: CityModel) -> AnyPublisher<WeatherForecastModel, Error>

}

struct RealWeatherWebRepository: WeatherWebRepository {
    
    let session: URLSession
    let baseURL: String
    let bgQueue = DispatchQueue(label: "bg_parse_queue")
    
    init(session: URLSession, baseURL: String) {
        self.session = session
        self.baseURL = baseURL
    }
    
    func fetchLiveWeather(city: CityModel) -> AnyPublisher<WeatherLiveModel, Error> {
        return call(endpoint: API.fetchLiveWeather(city))
    }
    
    func fetchForecastWeather(city: CityModel) -> AnyPublisher<WeatherForecastModel, Error> {
        return call(endpoint: API.fetchForecastWeather(city))
    }
}

// MARK: - Endpoints

extension RealWeatherWebRepository {
    enum API {
        case fetchLiveWeather(CityModel)
        case fetchForecastWeather(CityModel)

    }
}

extension RealWeatherWebRepository.API: APICall {
 
    var path: String {
        switch self {
        case let .fetchLiveWeather(city):
            return "?city=\(city.adcode)&extensions=base&key=\(NetworkingHelpers.secretKey)"
        case let .fetchForecastWeather(city):
            return "?city=\(city.adcode)&extensions=all&key=\(NetworkingHelpers.secretKey)"
        }
    }
    
    var method: String {
        switch self {
        case .fetchLiveWeather, .fetchForecastWeather:
            return "GET"
        }
    }
    
    var headers: [String: String]? {
        return ["Accept": "application/json"]
    }
    
    func body() throws -> Data? {
        return nil
    }
}

